import java.io.File;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import hyl.core.MyFun;

//https://blog.csdn.net/weixin_34148508/article/details/92601600
public class Webapp {
	public static void main(String[] args) {
		Webapp waWebapp = new Webapp();
		waWebapp.start();
	}

	// 虚拟路径
	private static String CONTEXT_PATH = "/em";
	// 项目根目录
	private static String PROJECT_PATH = System.getProperty("user.dir");
	// 虚拟路径指向的实际目录 也就是web程序的 jsp html js 文件存放目录
	private static String WEB_APP_PATH = MyFun.join(PROJECT_PATH, File.separatorChar, "WebRoot");
	// 动态编译后的jsp类目录
//	MyFun.join
	private static String CATALINA_HOME = MyFun.join2(File.separatorChar, PROJECT_PATH, "WebRoot", "WEB-INF",
			"classes");
	private Tomcat tomcat = new Tomcat();
	private int port = 8080;

	public void start() {

		tomcat.setPort(port);
		tomcat.setBaseDir(CATALINA_HOME);
		// tomcat.getHost().setAppBase(WEB_APP_PATH);//配置该项为了启用 web.xml配置 ,可以不配置
		tomcat.addWebapp(CONTEXT_PATH, WEB_APP_PATH);
		// tomcat.
		// 添加监听器
		// StandardServer server = (StandardServer)tomcat.getServer();
		// AprLifecycleListener listener = new AprLifecycleListener();
		// server.addLifecycleListener(listener);
		// 添加servlet
		// Tomcat.addServlet(context, "dispatch", httpServlet);
		// context.addServletMappingDecoded("/dispatch", "dispatch");
		// 添加过滤器
		// Filter filter = new MyFilter() ;
		// FilterDef filterDef = new FilterDef();
		// filterDef.setFilter(filter);
		// filterDef.setFilterName("myFilter");
		// filterDef.addInitParameter("userName", "Allen");
		// context.addFilterDef(filterDef);
		// 添加过滤器
		// FilterMap filterMap = new FilterMap();
		// filterMap.addURLPatternDecoded("/*");
		// filterMap.addServletName("*");
		// filterMap.setFilterName("myFilter");
		// filterMap.setCharset(MyCharset._UTF8);
		// context.addFilterMap(filterMap);
		try {
			tomcat.init();
			tomcat.start();
			tomcat.getServer().await();
		} catch (Exception e) {
			e.printStackTrace();

		}

	}

	public void stop() throws Exception {
		try {
			tomcat.stop();
		} catch (LifecycleException ex) {
			ex.printStackTrace();

			throw ex;
		}

	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getPort() {
		return this.port;
	}

}
